﻿using System;
using System.Globalization;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using System.Xml;
using System.Reflection;
using JigLibX.Physics;
using JigLibX.Collision;
using Services;
using Utilities.Menu.UIElements;
using TrenitaliaWP7.Resources;
using Services.Menu;
using Utilities;
using System.Windows;
using Microsoft.Phone.Tasks;
using System.Net;

namespace TrenitaliaWP7
{
    class DetailsMenu : OrientableScreen
    {

        Rectangle upperBox, lowerBox;
        ArrayList<Rectangle> rectangles;
        ArrayList<MyButton> rows;
        MyButton title;
        MyButton fromLabel, toLabel, fromTime, toTime, durationLabel, price1Label, price2Label, changesLabel;
        MyButton lastUpdate;
        InputManager input_manager;
        SpriteBatch spriteBatch;
        StateManager StateManager;
        //bool existsPopUp;
        SpriteFont font;
        Texture2D confirm, circle, WhitePixel;
        public Details chosen;
        Rectangle dragArea;
        bool dragging;
        MyButton updateInfo;
        public List<Train> trains;
        int pendingThread;
        bool refreshAborted;
        float velocity;
        float time_passed;
        float period;
        Texture2D emptyTexture;
        Texture2D questionMark;
        Texture2D box;
        SpriteFont titleFont;
        SpriteFont smallFont;
        SpriteFont verySmallFont;
        Texture2D back;
        Texture2D next;
        Texture2D refresh;
        Texture2D settings;
        Texture2D add_favorite, remove_favotite;
        Texture2D sendTexture;
        Texture2D buyTexture;
        MyButton favoritesButton;
        MyButton sendButton;
        MyButton buyButton;
        bool isFavorite;
        public bool isPrevMainMenu;
        bool vibration, allowVibration;
        Texture2D arrow;
        MyButton listTail, settingsButton;
        ArrayList<MyButton> timeSpansButton;
        ArrayList<Color> colors;
        ArrayList<String> SendByList;
        //ArrayList<MyButton> statusButtons;
        //bool isWorking;
        double startingTotalSeconds = 0;
        public DetailsMenu(Game game, Details chosen)
            : base(game)
        {
            this.chosen = chosen;
            if (chosen.trains == null || chosen.trains.Count == 0)
            {
                trains = new List<Train>();
                trains.Add(new Train(chosen.number, chosen.category));
                for (int i = 0; i < chosen.changes.Count; i++)
                {
                    trains.Add(new Train(chosen.changes[i].number, chosen.changes[i].category));
                }
            }
            else
            {
                trains = chosen.trains;
            }
            isPrevMainMenu = false;

        }
        public DetailsMenu(Game game, Details chosen, bool isPrevMainMenu)
            : base(game)
        {
            this.chosen = chosen;
            if (chosen.trains == null || chosen.trains.Count == 0)
            {
                trains = new List<Train>();
                trains.Add(new Train(chosen.number, chosen.category));
                for (int i = 0; i < chosen.changes.Count; i++)
                {
                    trains.Add(new Train(chosen.changes[i].number, chosen.changes[i].category));
                }
            }
            else
            {
                trains = chosen.trains;
            }
            this.isPrevMainMenu = isPrevMainMenu;
        }
        public DetailsMenu(Game game)
            : base(game)
        {
            this.chosen = new Details();
            trains = new List<Train>();
            isPrevMainMenu = false;
        }
        public override void Initialize()
        {
            //isWorking = false;
            vibration = false;
            allowVibration = false;
            spriteBatch = Game.Services.GetService(typeof(SpriteBatch)) as SpriteBatch;
            StateManager = Game.Services.GetService(typeof(AStateManager)) as StateManager;
            Game.Services.RemoveService(typeof(IInputManager));
            input_manager = new InputManager(Game);
            Game.Components.Add(input_manager);
            input_manager.OnTap += on_tap;
            input_manager.OnDrag += on_drag;
            input_manager.OnHorizontalDrag += on_drag;
            input_manager.OnVerticalDrag += on_drag;
            input_manager.OnDragCompleted += on_drag_completed;
            isFavorite = StateManager.Favorites.IsFavorite(chosen);

            if (isFavorite)
            {
                var possible_trains = StateManager.Favorites.GetFavouriteTrains(chosen);
                if (possible_trains != null && possible_trains.Count != 0)
                {
                    chosen.trains = possible_trains;
                    trains = chosen.trains;
                }
            }

            rows = new ArrayList<MyButton>();
            timeSpansButton = new ArrayList<MyButton>();
            rectangles = new ArrayList<Rectangle>();
            //statusButtons = new ArrayList<MyButton>();
            SendByList = new ArrayList<string>();
            SendByList.Add(Strings.SMS);
            SendByList.Add(Strings.E_mail);
            //SendByList.Add(Strings.E_mail_web);
            //smallFont = Game.Content.Load<SpriteFont>("Fonts/SegoeWP_Small");

            pendingThread = 0;
            velocity = 0;
            base.Initialize();


            dragging = false;

            time_passed = 0;
            switch (StateManager.OptionsState.autoUpdateMode)
            {
                case 1:
                    period = 60;
                    break;
                case 2:
                    period = 5 * 60;
                    break;
                case 3:
                    period = 10 * 60;
                    break;
                default:
                    period = 0;
                    break;

            }

            LoadColors();
        }
        private void LoadColors()
        {
            colors = new ArrayList<Color>();
            colors.Add(Color.LightGreen);
            colors.Add(Color.LightBlue);
            colors.Add(Color.LightCoral);
            colors.Add(Color.LightPink);
        }
        protected override void LoadContent()
        {
            emptyTexture = Game.Content.Load<Texture2D>("emptyPixel");
            box = Game.Content.Load<Texture2D>("bar_box");
            titleFont = Game.Content.Load<SpriteFont>("Fonts/SegoeWP_Title");
            smallFont = Game.Content.Load<SpriteFont>("Fonts/SegoeWP_Small");
            verySmallFont = Game.Content.Load<SpriteFont>("Fonts/SegoeWP_VerySmall");
            back = Game.Content.Load<Texture2D>("back");
            next = Game.Content.Load<Texture2D>("next");
            refresh = Game.Content.Load<Texture2D>("refresh");
            circle = Game.Content.Load<Texture2D>("circle");
            confirm = Game.Content.Load<Texture2D>("confirm");
            WhitePixel = Game.Content.Load<Texture2D>("WhitePixel");
            font = Game.Content.Load<SpriteFont>("Fonts/SegoeWP");
            add_favorite = Game.Content.Load<Texture2D>("add_fav");
            remove_favotite = Game.Content.Load<Texture2D>("remove_fav");
            arrow = Game.Content.Load<Texture2D>("arrow");
            sendTexture = Game.Content.Load<Texture2D>("send");
            buyTexture = Game.Content.Load<Texture2D>("buy");
            settings = Game.Content.Load<Texture2D>("settings");
            questionMark = Game.Content.Load<Texture2D>("credits");
            base.LoadContent();
        }
        public bool trial_finish = false;
        public override void Update(GameTime gameTime)
        {
            if (StateManager == null)
                SendCrashReport("1_state_manager_null");
            if (trial_finish)
            {
                StateManager.OpenAdvertisementsComponent();
                return;
            }

            else if (StateManager.Favorites == null)
                SendCrashReport("2_state_manager_Favorites_null");
            else if (chosen == null)
                SendCrashReport("3_choosen_null");
            //else
            isFavorite = StateManager.Favorites.IsFavorite(chosen);


            if (!StateManager.isTrial && favoritesButton != null)
                favoritesButton.texture = isFavorite ? remove_favotite : add_favorite;

            if (StateManager.isTrial)
            {
                if (startingTotalSeconds == 0)
                    startingTotalSeconds = gameTime.TotalGameTime.TotalSeconds;
                if (gameTime.TotalGameTime.TotalSeconds - startingTotalSeconds > 30)
                {
                    StateManager.StartVibration(new TimeSpan(0, 0, 0, 0, 500));
                    //StateManager.OpenAdvertisementsComponent();
                    if (!trial_finish)
                    {
                        if (MessageBox.Show(Strings.TrialTime, "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                        {

                            trial_finish = true;
                            OpenMarket(Game1.APP_ID);
                            Thread.Sleep(2000);


                        }
                        else
                            StateManager.OpenAdvertisementsComponent();
                    }
                    return;
                }
            }
            float dt = (float)gameTime.ElapsedGameTime.TotalSeconds;
            if (period != 0)
            {
                time_passed += dt;
                if (time_passed >= period)
                {
                    time_passed = 0;
                    RefreshData();
                }
            }
            if (vibration && allowVibration)
            {
                StateManager.StartVibration(new TimeSpan(0, 0, 0, 0, 500));
                vibration = false;
                allowVibration = false;
            }
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)// && !existsPopUp)
            {
                if (StateManager.isTrial)
                {
                    //StateManager.OpenAdvertisementsComponent();

                    if (MessageBox.Show(Strings.TrialTime, "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                    {
                        //trial_finish = true;
                        OpenMarket(Game1.APP_ID);
                        //Thread.Sleep(2000);
                    }
                    else
                        StateManager.OpenAdvertisementsComponent();
                }
                else
                {
                    if (isPrevMainMenu)
                        StateManager.SelectMainMenu2();
                    else
                        StateManager.OpenResultMenu();
                }
            }


            if (velocity != 0 && !dragging)
            {
                if (velocity < 0)
                {
                    velocity += dt * 2;
                    if (velocity > 0)
                        velocity = 0;
                }
                else
                {
                    velocity -= dt * 2;
                    if (velocity < 0)
                        velocity = 0;
                }
                //if (Math.Abs(velocity) < 0.5f)
                //    velocity = 0;
                var delta_y = (int)velocity;

                //if (rows == null)
                //    SendCrashReport("5_rows_null");
                //else if (rows.Count > 0 && rows[0] == null)
                //    SendCrashReport("6_rows_0_null");
                //else if (rows.Count > 0 && rows[0].rectangle == null)
                //    SendCrashReport("7_rows_0_rectangle_null");
                //else if (dragArea == null)
                //    SendCrashReport("8_dragArea_null");
                //else if (listTail == null)
                //    SendCrashReport("9_listTail_null");
                //else if (listTail.rectangle == null)
                //    SendCrashReport("10_listTail_rectangle_null");



                //else
                if (rows.Count > 0 && rows[0].rectangle.Y > dragArea.Y)
                {
                    velocity = 0;
                    delta_y = dragArea.Y - rows[0].rectangle.Y;
                }
                else if (rows.Count > 0 && listTail.rectangle.Y + listTail.rectangle.Height < dragArea.Y + dragArea.Height)
                //if (rows.Count > 0 && rows[rows.Count - 1].rectangle.Y + rows[rows.Count - 1].rectangle.Height < dragArea.Y + dragArea.Height)
                {
                    velocity = 0;
                    delta_y = dragArea.Y + dragArea.Height - listTail.rectangle.Y - listTail.rectangle.Height;
                    //delta_y = dragArea.Y + dragArea.Height - rows[rows.Count - 1].rectangle.Y - rows[rows.Count - 1].rectangle.Height;
                    if (rows[0].rectangle.Y + delta_y > dragArea.Y)
                    {
                        delta_y = dragArea.Y - rows[0].rectangle.Y;
                    }
                }

                if (rows == null)
                    SendCrashReport("11_rows_null");
                //else
                for (int i = 0; i < rows.Count; i++)
                {
                    if (rows[i] == null)
                        SendCrashReport("12_rows_" + i + "_null");
                    rows[i].rectangle.Y += delta_y;
                    rows[i].UpdateTextPos();
                }

            }


            base.Update(gameTime);
        }
        public override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.Black);
            if (spriteBatch == null)
                return;
            spriteBatch.Begin();

            if (WhitePixel != null)
            {
                for (int i = 0; i < rectangles.Count; i++)
                {
                    spriteBatch.Draw(WhitePixel, rectangles[i], Color.DarkGray);
                }
                for (int i = 0; i < rows.Count; i++)
                {
                    if (rows[i] != null)
                        rows[i].Draw(spriteBatch);
                }
                if (upperBox != null)
                    spriteBatch.Draw(WhitePixel, upperBox, Color.Black);

                if (lowerBox != null)
                    spriteBatch.Draw(WhitePixel, lowerBox, Color.Black);
            }
            if (title != null)
                title.Draw(spriteBatch);

            if (fromLabel != null)
                fromLabel.Draw(spriteBatch);

            if (fromTime != null)
                fromTime.Draw(spriteBatch);

            if (toLabel != null)
                toLabel.Draw(spriteBatch);

            if (toTime != null)
                toTime.Draw(spriteBatch);

            if (durationLabel != null)
                durationLabel.Draw(spriteBatch);

            if (changesLabel != null)
                changesLabel.Draw(spriteBatch);

            if (price1Label != null)
                price1Label.Draw(spriteBatch);

            if (price2Label != null)
                price2Label.Draw(spriteBatch);

            if (updateInfo != null)
                updateInfo.Draw(spriteBatch);

            if (favoritesButton != null)
                favoritesButton.Draw(spriteBatch);

            if (settingsButton != null)
                settingsButton.Draw(spriteBatch);

            if (lastUpdate != null)
                lastUpdate.Draw(spriteBatch);

            if (sendButton != null)
                sendButton.Draw(spriteBatch);

            if (buyButton != null)
                buyButton.Draw(spriteBatch);

            spriteBatch.End();
            base.Draw(gameTime);
        }

        void on_tap(Vector2 tap_position)
        {
            if (press_wait < PRESS_INTERVAL/* || existsPopUp*/) return;
            if (StateManager.isTrial)
            {
                if (RectContaintsVect(Game1.trial_rectangle, tap_position))
                {
                    OpenMarket(Game1.APP_ID);
                    return;
                }
            }
            if (updateInfo.tapped_on(tap_position))
                RefreshData();
            else if (favoritesButton != null && favoritesButton.tapped_on(tap_position))
            {

                //PER VERIFICARE CRASH
                //object a = null;
                //a.ToString();
                //SendCrashReport("bla");


                if (isFavorite)
                {
                    //StateManager.OpenPopUp(RemoveFavorite, ClosePopUp, Strings.RemoveFromFavorites, "", Strings.Yes, Strings.No, font, box, WhitePixel, Color.Black);
                    //input_manager.Enabled = false;
                    //Game.Components.Remove(input_manager);
                    //existsPopUp = true;

                    bool ok = StateManager.OpenQuestionPopUp(Strings.RemoveFromFavorites);
                    if (ok)
                        RemoveFavorite();

                    isFavorite = false;
                    favoritesButton.texture = add_favorite;
                    return;
                }
                else
                {
                    isFavorite = true;
                    StateManager.Favorites.AddFavorite(chosen);
                    Storage.SaveFavorites(StateManager.Favorites);
                    favoritesButton.texture = remove_favotite;
                    return;
                }
                //favoritesButton.texture = isFavorite ? remove_favotite : add_favorite;
                //return;
            }
            else if (settingsButton.tapped_on(tap_position))
            {
                input_manager.Enabled = false;
                StateManager.SelectOptionsMenu(false);
            }
            else if (sendButton != null && sendButton.tapped_on(tap_position))
            {
                this.Enabled = false;
                input_manager.Enabled = false;
                StateManager.OpenItemListComponent(CloseSendTypeSelector, AbortSendTypeSelector, Strings.SendBy, SendByList);
            }
            else if (buyButton != null && buyButton.tapped_on(tap_position))
            {
                if (chosen.buy_query == "")
                    MessageBox.Show(Strings.MissingUrl);
                else if((price1Label!=null && price1Label.text=="") && (price2Label!=null && price2Label.text==""))
                {
                    MessageBox.Show(Strings.NoBuyable);
                }
                else
                    if (MessageBox.Show(Strings.OpenWebSite, "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                    {
                        OpenWebsite();
                    }
            }
            else
            {
                for (int i = 0; i < rows.Count; i++)
                {
                    var b = rows[i];
                    if (b.font == null && b.text != "" && b.tapped_on(tap_position))
                    {
                        for (int j = 0; j < trains.Count; j++)
                        {
                            if (trains[j].number == b.text && trains[j].status != "")
                            {
                                MessageBox.Show(trains[j].status);
                                break;
                            }
                        }
                        break;
                    }
                }
            }
        }
        void OpenWebsite()
        {
            try
            {
                var s = chosen.buy_query;
                WebBrowserTask task = new WebBrowserTask();
                s = Uri.EscapeUriString(s);
                //task.URL = s;
                //task.URL = HttpUtility.UrlEncode("http://orario.trenitalia.com/b2c/nppTravelChoice.do?lang=it&stazin=treviso&stazout=marghera&datag=18&datam=04&dataa=2011&timsh=16&timsm=00&nreq=5&stazin_r=Staz_DA&stazout_r=Staz_A&datag_r=&datam_r=&dataa_r=&timsh_r=&timsm_r=00&nreq_r=5&npag=1&sort=0&economy=0&det=3&solotreno=0&noreservation=0&traintype=&car=0&dc=1");
                //task.URL = HttpUtility.UrlEncode(s);
                task.Uri = new Uri(s, UriKind.Absolute);
                task.Show();
            }
            catch (Exception e)
            {
                e.ToString();
                MessageBox.Show(Strings.UnableToLoadWebsite);
                return;
            }
        }
        void CloseSendTypeSelector(String type)
        {
            this.Enabled = true;
            input_manager.Enabled = true;
            if (type == Strings.SMS)
            {
                try
                {
                    SmsComposeTask sms = new SmsComposeTask();
                    chosen.trains = trains;
                    sms.Body = chosen.ToSMS();
                    sms.Show();
                }
                catch(Exception e)
                {
                    e.ToString();
                }
            }
            else if (type == Strings.E_mail)
            {
                try
                {
                    EmailComposeTask email = new EmailComposeTask();
                    chosen.trains = trains;
                    email.Subject = chosen.ToEMailSubject();
                    email.Body = chosen.ToEMail();
                    email.Show();
                }
                catch(Exception e)
                {
                    e.ToString();
                }

            }
            //else if (type == Strings.E_mail_web)
            //{
            //    EmailComposeTask email = new EmailComposeTask();
            //    chosen.trains = trains;
            //    email.Subject = chosen.ToEMailSubject();
            //    email.Body = chosen.ToEMail_Webpage();

            //    email.Show();

            //}
        }
        void AbortSendTypeSelector()
        {
            this.Enabled = true;
            input_manager.Enabled = true;
        }
        void RemoveFavorite()
        {
            isFavorite = false;
            StateManager.Favorites.RemoveFavorite(chosen);
            Storage.SaveFavorites(StateManager.Favorites);
            //ClosePopUp();
            favoritesButton.texture = add_favorite;
        }
        Vector2 prev_drag_pos;

        void on_drag(Vector2 drag_pos)
        {
            if (prev_drag_pos != Vector2.Zero)
            {
                if (!RectContainsVect(dragArea, drag_pos))
                {
                    dragging = false;
                }
                else
                {
                    int offset = (int)(drag_pos.Y - prev_drag_pos.Y);
                    for (int i = 0; i < rows.Count; i++)
                    {
                        rows[i].rectangle.Y += offset;
                        rows[i].UpdateTextPos();
                    }
                    velocity = offset;
                }
            }
            else
            {
                if (RectContainsVect(dragArea, drag_pos))
                {
                    dragging = true;
                }

            }
            prev_drag_pos = drag_pos;
        }
        void on_drag_completed()
        {
            prev_drag_pos = Vector2.Zero;
            dragging = false;
            if (velocity == 0 && rows.Count > 0 && listTail.rectangle.Y + listTail.rectangle.Height > dragArea.Y + dragArea.Height)
                velocity = 0.01f;

        }
        public bool RectContainsVect(Rectangle rect, Vector2 v)
        {
            return rect.X < v.X && rect.Y < v.Y && rect.X + rect.Width > v.X && rect.Y + rect.Height > v.Y;
        }

        public void RefreshData()
        {
            if (pendingThread > 0)
                return;
            //isWorking = true;
            refreshAborted = false;
            pendingThread = 0;
            time_passed = 0;
            allowVibration = StateManager.OptionsState.vibration;
            for (int i = 0; i < trains.Count; i++)
            {
                startHTMLRequest(Utilities.ComputeDetailsUrl(trains[i].number), trains[i].number);
                startHTMLRequest2(Utilities.ComputeDelayUrl(trains[i].number), trains[i].number);
            }
        }
        void AbortRefresh()
        {
            refreshAborted = true;
            this.Enabled = true;
            //isWorking = false;
            pendingThread = 0;
            ChangeOrientation();
        }
        void startHTMLRequest(string query, string number)
        {
            if (pendingThread == 0)
                StateManager.OpenLoadingComponent(this, AbortRefresh);
            pendingThread++;
            new Thread(new ThreadStart(() =>
            {
                Utilities.getHTML(query, number, GotHTML, ErrorGettingHTML);
            })).Start();
        }
        //void ClosePopUp()
        //{
        //    existsPopUp = false;
        //    input_manager.Enabled = true;
        //    Game.Components.Add(input_manager);
        //    press_wait = 0;
        //}
        void GotHTML(string html, string number)
        {
            if (refreshAborted)
                return;
            pendingThread--;


            //HTMLPaser parser = new HTMLPaser(html);
            try
            {
                DetailsParser parser = new DetailsParser(html);
                var newResult = parser.GetTrainDetail();

                for (int i = 0; i < trains.Count; i++)
                {
                    if ((trains[i].number.Equals(newResult.number) || trains[i].number == number) && newResult.number != "")
                    //var a = String.Compare(trains[i].number, newResult.number);
                    //if (a==0)
                    {
                        newResult.type = trains[i].type;
                        trains[i] = newResult;
                        //ChangeOrientation();



                        break;
                    }
                }
            }
            catch (Exception e)
            {
                e.ToString();
                MessageBox.Show(Strings.ErrorGettingData);
            }
            if (pendingThread <= 0)
            {
                StateManager.CloseLoadingComponent(this);
                //isWorking = false;
                chosen.lastUpdate = DateTime.Now;
                //if (updateInfo != null)
                //    updateInfo.alpha = 1;
                if (isFavorite)
                {
                    chosen.trains = trains;
                    try
                    {
                            Storage.SaveFavorites(StateManager.Favorites);
                    }
                    catch (Exception e)
                    { e.ToString(); }
                }
                ChangeOrientation();
            }
        }

        void startHTMLRequest2(string query, string number)
        {
            if (pendingThread == 0)
                StateManager.OpenLoadingComponent(this, AbortRefresh);
            pendingThread++;
            new Thread(new ThreadStart(() =>
            {
                Utilities.getHTML(query, number, GotHTML2, ErrorGettingHTML);
            })).Start();
        }
        void GotHTML2(string html, string number)
        {
            if (refreshAborted)
                return;
            pendingThread--;


            //HTMLPaser parser = new HTMLPaser(html);
            try
            {
                DelayParser parser = new DelayParser(html);
                var delay = parser.GetTrainDelay();
                var status = parser.GetStatus();
                for (int i = 0; i < trains.Count; i++)
                {
                    if (trains[i].number == number)
                    {
                        trains[i].delay = delay;
                        trains[i].status = status;
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                e.ToString();
                MessageBox.Show(Strings.ErrorGettingData);
            }
            if (pendingThread <= 0)
            {
                StateManager.CloseLoadingComponent(this);
                chosen.lastUpdate = DateTime.Now;
                if (isFavorite)
                    try
                    {
                        
                        Storage.SaveFavorites(StateManager.Favorites);
                    }
                    catch (Exception e)
                    {
                        e.ToString();
                    }

                ChangeOrientation();
            }
        }

        void ErrorGettingHTML()
        {
            StateManager.CloseLoadingComponent(this);
            pendingThread = 0;
            //StateManager.OpenErrorPopUp(ClosePopUp, Strings.ErrorGettingData, "", font, confirm, circle, WhitePixel, Color.Black);
            //input_manager.Enabled = false;
            //Game.Components.Remove(input_manager);
            //existsPopUp = true;
            System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
            { StateManager.OpenNotifyPopUp(Strings.ErrorGettingData); });
            return;
        }
        public override void SetPortraitOrientation()
        {

            title = new MyButton(new Rectangle(20, 20, 200, 80), Strings.Details, Color.White, titleFont, TextPos.Left);
            upperBox = new Rectangle(0, 0, 480, 300);
            lowerBox = new Rectangle(0, 720, 480, 80);
            fromLabel = new MyButton(new Rectangle(20, 80, 200, 60), chosen.from, Color.White, smallFont);
            toLabel = new MyButton(new Rectangle(260, 80, 200, 60), chosen.to, Color.White, smallFont);

            fromTime = new MyButton(new Rectangle(20, 120, 200, 60), chosen.departure, Color.White, smallFont);
            toTime = new MyButton(new Rectangle(260, 120, 200, 60), chosen.arrival, Color.White, smallFont);

            durationLabel = new MyButton(new Rectangle(20, 180, 200, 60), Strings.Duration + chosen.duration, Color.White, smallFont);
            var s = chosen.changes.Count == 0 ? "" : Strings.Changes + chosen.changes.Count;
            changesLabel = new MyButton(new Rectangle(20, 210, 200, 60), s, Color.White, smallFont);
            s = chosen.price1 == "" ? "" : Strings.Price1 + chosen.price1 + " €";
            price1Label = new MyButton(new Rectangle(260, 180, 200, 60), s, Color.White, smallFont);
            s = chosen.price2 == "" ? "" : Strings.Price2 + chosen.price2 + " €";
            price2Label = new MyButton(new Rectangle(260, 210, 200, 60), s, Color.White, smallFont);

            lastUpdate = new MyButton(new Rectangle(40, 245, 400, 60),
                Strings.LastUpdate + chosen.lastUpdate.ToString(), Color.White, smallFont);



            if (StateManager.isTrial)
            {
                settingsButton = new MyButton(new Rectangle(125, 730, 50, 50), settings, Color.White, circle, Color.White);
                updateInfo = new MyButton(new Rectangle(215, 730, 50, 50), refresh, Color.White, circle, Color.White);

                favoritesButton = null;
                sendButton = new MyButton(new Rectangle(305, 730, 50, 50), sendTexture, Color.White, circle, Color.White);
                buyButton = null;
            }
            else
            {
                //settingsButton = new MyButton(new Rectangle(80, 730, 50, 50), settings, Color.White, circle, Color.White);
                //updateInfo = new MyButton(new Rectangle(170, 730, 50, 50), refresh, Color.White, circle, Color.White);
                //favoritesButton = new MyButton(new Rectangle(260, 730, 50, 50), isFavorite ? remove_favotite : add_favorite, Color.White, circle, Color.White);
                //sendButton = new MyButton(new Rectangle(350, 730, 50, 50), sendTexture, Color.White, circle, Color.White);

                settingsButton = new MyButton(new Rectangle(55, 730, 50, 50), settings, Color.White, circle, Color.White);
                updateInfo = new MyButton(new Rectangle(135, 730, 50, 50), refresh, Color.White, circle, Color.White);
                favoritesButton = new MyButton(new Rectangle(215, 730, 50, 50), isFavorite ? remove_favotite : add_favorite, Color.White, circle, Color.White);
                sendButton = new MyButton(new Rectangle(295, 730, 50, 50), sendTexture, Color.White, circle, Color.White);

                buyButton = new MyButton(new Rectangle(375, 730, 50, 50), buyTexture, Color.White, circle, Color.White);
            }
            int initial_y = 280;


            int name_x = 30;
            int stops_x = 60;
            int times_x = 300;
            int binary_x = 430;
            int name_width = 440;
            int name_height = 60;
            int rows_height = 40;
            int stops_width = 260;
            int times_width = 60;
            int binary_width = 40;
            dragArea = new Rectangle(0, upperBox.Height, 480, 800 - upperBox.Height - lowerBox.Height);
            CreateRows(initial_y, name_x, stops_x, times_x, binary_x, name_width, name_height,
             rows_height, stops_width, times_width, binary_width, smallFont, 5);
            //dragArea = new Rectangle(0, upperBox.Height, 480, 800 - upperBox.Height);

        }
        ArrayList<MyButton> buttonsArrows = new ArrayList<MyButton>();
        void CreateRows(int initial_y, int name_x, int stops_x, int times_x, int binary_x, int name_width, int name_height,
            int rows_height, int stops_width, int times_width, int binary_width, SpriteFont font, int arrow_x)
        {
            rows.Clear();
            int y = initial_y;
            var now = DateTime.Now.TimeOfDay;
            buttonsArrows.Clear();
            //statusButtons.Clear();
            for (int i = 0; i < trains.Count; i++)
            {
                timeSpansButton.Clear();
                var t = trains[i];
                var newStatusButton = new MyButton(new Rectangle(name_x, y, name_width, 0), emptyTexture, Color.White);

                bool skipFirsts = !StateManager.OptionsState.showCompletePaths;
                bool skipLasts = !StateManager.OptionsState.showCompletePaths;
                var s = t.type + " " + t.number;
                if (t.delay != "")
                    s += " - " + Strings.Delay + t.delay + " " + (t.delay == "1" ? Strings.Minute : Strings.Minutes);
                listTail = new MyButton(new Rectangle(name_x, y, name_width, name_height), s, Color.White, font);
                if (t.status != "" && CultureInfo.CurrentCulture.TwoLetterISOLanguageName.Equals("it"))
                {
                    var val = (int)(name_height / 1.5);
                    rows.Add(new MyButton(new Rectangle(name_x + name_width - val, y + name_height / 2 - val / 2, val, val), questionMark, Color.White, circle, Color.White));
                }
                rows.Add(listTail);
                y += name_height;

                for (int j = 0; j < t.stops.Count; j++)
                {
                    s = t.stops[j];
                    if (StateManager.OptionsState.showAlwaysTimes)
                        s = s.Substring(0, Math.Min(15, s.Length));
                    else
                        s = s.Substring(0, Math.Min(20, s.Length));
                    var n = new MyButton(new Rectangle(stops_x, y, stops_width, rows_height), s, Color.White, font, TextPos.Left);//, box, Color.White);
                    n.adjustVerticalAlignement = true;
                    n.UpdateTextPos();
                    //s = 

                    if (i > 0)
                    {
                        var coincidence = trains[i - 1].stops.Contains(t.stops[j]);
                        if (skipFirsts)
                        {
                            if (!coincidence)
                            {
                                //index1 = j + 1;
                                continue;
                            }
                        }
                        if (coincidence)
                        {
                            //n.textColor = Color.Green;
                            n.textColor = colors[(i - 1) % colors.Count];
                            skipFirsts = false;
                            //if (index1 == 0)
                            //    index1 = j;
                        }
                    }

                    rows.Add(n);
                    s = t.real_times[j];
                    if (s == "" || s == "--")
                        s = t.times[j];

                    //var printed_s = s;
                    if (StateManager.OptionsState.showAlwaysTimes)
                    {
                        //printed_s = s == t.times[j] ? s : "(" + t.times[j] + ") " + s;
                        if (s != t.times[j])
                            rows.Add(new MyButton(new Rectangle(times_x, y, times_width, rows_height),
                                "(" + t.times[j] + ")",
                                Color.White,
                                font)
                            );

                        var ts = new MyButton(new Rectangle(times_x + times_width, y, times_width, rows_height),
                            //printed_s,
                            s,
                            //s == t.times[j] ? Color.White : Color.Red, font
                            Color.Red,
                            font
                        );
                        rows.Add(ts);
                        vibration = vibration || s != t.times[j];
                        timeSpansButton.Add(ts);
                    }
                    else
                    {
                        var ts = new MyButton(new Rectangle(times_x, y, times_width * 2, rows_height),
                            //printed_s,
                            s,
                            s == t.times[j] ? Color.White : Color.Red, font);
                        rows.Add(ts);
                        vibration = vibration || s != t.times[j];
                        timeSpansButton.Add(ts);
                    }

                    if (t.cancelled[j])
                        s = Strings.Cancelled;
                    else
                    {
                        s = t.real_binary[j];
                        if (s == "" || s == "--")
                            s = t.binary[j];
                    }
                    listTail = new MyButton(new Rectangle(binary_x, y, binary_width, rows_height), s, s == t.binary[j] ? Color.White : Color.Red, font);
                    rows.Add(listTail);
                    vibration = vibration || s != t.binary[j];
                    y += rows_height;
                    if (i + 1 < trains.Count)
                    {
                        if (trains[i + 1].stops.Contains(t.stops[j]))
                        {
                            //n.textColor = Color.Green;
                            if (colors == null)
                            {
                                LoadColors();
                            }
                            n.textColor = colors[i % colors.Count];
                        }

                        if (skipLasts && trains[i + 1].stops.Count > 0)
                        {
                            bool end = true;
                            for (int z = j + 1; z < t.stops.Count; z++)
                                if (trains[i + 1].stops.Contains(t.stops[z]))
                                    end = false;
                            if (end)
                            {
                                //index2 = j;
                                break;
                            }
                        }
                    }
                    else
                    {
                        if (skipLasts && t.stops[j] == chosen.to)
                        {
                            //index2 = j;
                            break;
                        }
                    }
                }


                if (t.stops.Count > 0 && timeSpansButton.Count > 0)// && index < t.stops.Count)
                {

                    MyButton a = timeSpansButton[0];
                    var ts = getTimeSpan(timeSpansButton[0].text);
                    int offset = 0;
                    if (now > ts)
                    {
                        int index = 0;
                        //var now = DateTime.Now.TimeOfDay;
                        for (int j = 1; j < timeSpansButton.Count; j++)
                        {
                            ts = getTimeSpan(timeSpansButton[j].text);
                            if (now > ts)
                            {
                                a = timeSpansButton[j];
                                index = j;
                                //break;
                            }
                            else
                                break;
                        }

                        if (index < timeSpansButton.Count - 1)
                        {
                            var ts1 = getTimeSpan(timeSpansButton[index].text);
                            var ts2 = getTimeSpan(timeSpansButton[index + 1].text);
                            if (ts1 != TimeSpan.Zero && ts2 != TimeSpan.Zero)
                            {
                                var delta = (ts2 - ts1).Minutes;
                                var trascorso = (now - ts1).Minutes;
                                if (delta == 0)
                                {
                                    delta = 1;
                                    trascorso = 0;
                                }
                                //altezza riga : offset = delta : tempo_passato
                                // offset = altezza * tempo_passato / delta
                                offset = rows_height * trascorso / delta;
                            }
                        }
                    }
                    Color arrowColor = Color.White;
                    if (a != timeSpansButton[0] && a != timeSpansButton[timeSpansButton.Count - 1])
                        arrowColor = Color.Red;
                    int y_arrow = a.rectangle.Center.Y - 20 + offset;
                    rows.Add(new MyButton(new Rectangle(arrow_x, y_arrow, 50, 40), arrow, arrowColor));
                    buttonsArrows.Add(a);


                }
                newStatusButton.text = t.number;
                newStatusButton.rectangle.Height = y - newStatusButton.rectangle.Y;
                if (t.status != "" && CultureInfo.CurrentCulture.TwoLetterISOLanguageName.Equals("it"))
                    rows.Add(newStatusButton);
            }

            int delta_y = 0;
            for (int i = 0; i < buttonsArrows.Count; i++)
            {
                var ts = getTimeSpan(buttonsArrows[i].text);
                if (now < ts)
                    break;
                delta_y = dragArea.Y - buttonsArrows[i].rectangle.Y;
                velocity = 0.001f;
            }
            if (delta_y != 0)
                for (int i = 0; i < rows.Count; i++)
                    rows[i].rectangle.Y += delta_y;
        }
        TimeSpan getTimeSpan(string s)
        {
            if (s == "" || s == "--")
            {
                return TimeSpan.Zero;
            }
            try
            {
                if (s.Contains(")"))
                {
                    s = s.Split(')')[1];
                }
                var v = s.Split(':');

                if (v.Length != 2)
                    return TimeSpan.Zero;
                int h = Int16.Parse(v[0]);
                int m = Int16.Parse(v[1]);
                return new TimeSpan(h, m, 0);
            }
            catch (Exception e)
            {
                e.ToString();
                return TimeSpan.Zero;
            }
        }
        public override void SetLandScapeOrientation()
        {

            title = new MyButton(new Rectangle(80, 20, 200, 60), Strings.Details, Color.White, titleFont, TextPos.Left);
            upperBox = new Rectangle(0, 0, 800, 220);
            lowerBox = new Rectangle(0, 480, 800, 0);
            fromLabel = new MyButton(new Rectangle(160, 60, 150, 60), chosen.from, Color.White, smallFont);
            toLabel = new MyButton(new Rectangle(480, 60, 150, 60), chosen.to, Color.White, smallFont);

            fromTime = new MyButton(new Rectangle(290, 60, 150, 60), chosen.departure, Color.White, smallFont);
            toTime = new MyButton(new Rectangle(630, 60, 150, 60), chosen.arrival, Color.White, smallFont);

            durationLabel = new MyButton(new Rectangle(80, 100, 300, 60), Strings.Duration + chosen.duration, Color.White, smallFont);
            var s = chosen.changes.Count == 0 ? "" : Strings.Changes + chosen.changes.Count;
            changesLabel = new MyButton(new Rectangle(80, 130, 300, 60), s, Color.White, smallFont);
            s = chosen.price1 == "" ? "" : Strings.Price1 + chosen.price1 + " €";
            price1Label = new MyButton(new Rectangle(420, 100, 300, 60), s, Color.White, smallFont);
            s = chosen.price2 == "" ? "" : Strings.Price2 + chosen.price2 + " €";
            price2Label = new MyButton(new Rectangle(420, 130, 300, 60), s, Color.White, smallFont);

            lastUpdate = new MyButton(new Rectangle(100, 165, 700, 60),
                Strings.LastUpdate + chosen.lastUpdate.ToString(), Color.White, smallFont);



            if (StateManager.isTrial)
            {
                settingsButton = new MyButton(new Rectangle(25, 125, 50, 50), settings, Color.White, circle, Color.White);
                updateInfo = new MyButton(new Rectangle(25, 215, 50, 50), refresh, Color.White, circle, Color.White);

                favoritesButton = null;
                sendButton = new MyButton(new Rectangle(25, 305, 50, 50), sendTexture, Color.White, circle, Color.White);
                buyButton = null;
            }
            else
            {

                //settingsButton = new MyButton(new Rectangle(25, 80, 50, 50), settings, Color.White, circle, Color.White);
                //updateInfo = new MyButton(new Rectangle(25, 170, 50, 50), refresh, Color.White, circle, Color.White);
                //favoritesButton = new MyButton(new Rectangle(25, 260, 50, 50), isFavorite ? remove_favotite : add_favorite, Color.White, circle, Color.White);
                //sendButton = new MyButton(new Rectangle(25, 350, 50, 50), sendTexture, Color.White, circle, Color.White);

                settingsButton = new MyButton(new Rectangle(25, 55, 50, 50), settings, Color.White, circle, Color.White);
                updateInfo = new MyButton(new Rectangle(25, 135, 50, 50), refresh, Color.White, circle, Color.White);
                favoritesButton = new MyButton(new Rectangle(25, 215, 50, 50), isFavorite ? remove_favotite : add_favorite, Color.White, circle, Color.White);
                sendButton = new MyButton(new Rectangle(25, 295, 50, 50), sendTexture, Color.White, circle, Color.White);
                buyButton = new MyButton(new Rectangle(25, 375, 50, 50), buyTexture, Color.White, circle, Color.White);
            }
            int initial_y = 200;


            int name_x = 200;
            int stops_x = 220;
            int times_x = 500;
            int binary_x = 700;
            int name_width = 600;
            int name_height = 60;
            int rows_height = 40;
            int stops_width = 300;
            int times_width = 100;
            int binary_width = 100;
            dragArea = new Rectangle(0, upperBox.Height, 800, 480 - upperBox.Height - lowerBox.Height);
            CreateRows(initial_y, name_x, stops_x, times_x, binary_x, name_width, name_height,
             rows_height, stops_width, times_width, binary_width, smallFont, 130);
        }

        public int getRowsOffset()
        {
            if (rows.Count > 0)
                return rows[0].rectangle.Y;
            return 0;
        }
        public void setRowsOffset(int val)
        {
            if (rows.Count == 0)
                return;
            var delta_y = rows[0].rectangle.Y - val;
            //var delta_y = upperBox.Y - value;
            for (int i = 0; i < rows.Count; i++)
                rows[i].rectangle.Y -= delta_y;
        }

        #region CrashReport

        string FixDateString(string s)
        {
            string s1 = s.Replace('/', '-').Replace(':', '-').Replace(' ', '_');
            return s1;
        }

        void SendCrashReport(string s)
        {
            //return;
            var url = "http://fboscari.altervista.org/submit_string.php/?tab=CrashReports&applicazione=InformaTreni&dataora=" +
                FixDateString(DateTime.Now.ToString()) + "&stringa=" + s;
            new Thread(new ThreadStart(() =>
            {
                Utilities.getHTML(url, (s1) => { }, () => { });
            })).Start();

        }


        #endregion
    }
}
